const { Schema, model } = require('mongoose');

// 创建一个通用的 Schema  
const BaseSchema = new Schema({
  createdAt: {
    type: Date,
    default: Date.now,
  },
  updatedAt: {
    type: Date,
    default: Date.now,
  },
});

// 扩展 Schema 以添加更新时间戳的中间件
BaseSchema.pre('save', function (next) {
  if (this.isModified('updatedAt')) {
    this.updatedAt = new Date().toISOString();
  }
  next();
});

// 封装基本的 CRUD 操作
class MongooseHelper {
  constructor(name, schema) {
    this.Model = model(name, schema);
  }

  async create (data) {
    try {
      const newDoc = new this.Model(data);
      await newDoc.save();
      return newDoc;
    } catch (error) {
      throw error;
    }
  }

  async read (_id) {
    try {
      if (_id) {
        return await this.Model.findById(_id).exec();
      }
      return await this.Model.find().exec();
    } catch (error) {
      throw error;
    }
  }
  async find (query) {
    try {
      return await this.Model.find(query).exec();
    } catch (error) {
      throw error;
    }
  }
  async update (_id, data) {
    try {
      const updatedDoc = await this.Model.findByIdAndUpdate(_id, data, { new: true }).exec();
      if (!updatedDoc) {
        throw new Error('Document not found');
      }
      return updatedDoc;
    } catch (error) {
      throw error;
    }
  }

  async delete (_id) {
    try {
      const deletedDoc = await this.Model.findByIdAndDelete(_id).exec();
      if (!deletedDoc) {
        throw new Error('Document not found');
      }
      return deletedDoc;
    } catch (error) {
      throw error;
    }
  }
}

module.exports = { MongooseHelper, BaseSchema };